<template>
  <div class="flex flex-col h-full">
    <SearchContainer @search="getData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" :model="formState">
        <a-form-item name="categoryName" label="">
          <a-input v-model:value="formState.categoryName" placeholder="类别名称" class="w-64" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card :bordered="false" class="mt-2 flex-1" size="small">
      <div class="mb-3">
        <a-button type="primary" class="" ghost @click="onExpandAll">
          <component :is="Icon[isExpandAll ? 'CaretDownOutlined' : 'CaretRightOutlined']" /> {{ isExpandAll ? '折叠全部' : '展开全部' }}
        </a-button>
      </div>

      <BaseTable v-model:expanded-row-keys="expandedRowKeys" column-code="000365" row-key="id" :loading="loading" :data-source="tableData" bordered fill>
        <template #expandIcon="{ expanded, record, onExpand }">
          <component
            :is="Icon[expanded ? 'CaretDownOutlined' : 'CaretRightOutlined']"
            v-if="record.children?.length"
            class="px-1"
            @click="onExpand(record, $event)"
          />
        </template>
        <!-- <template #bodyCell="{ column, expanded, record, onExpand }">
          <template v-if="column.dataIndex === 'categroyName'">
            <component
              :is="Icon[expanded ? 'CaretDownOutlined' : 'CaretRightOutlined']"
              v-if="record.children?.length"
              class="px-1"
              @click="onExpand(record, $event)"
            />
            {{ record.categroyName }}
          </template>
        </template> -->
      </BaseTable>
    </a-card>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import * as Icon from '@ant-design/icons-vue'
import { post } from '@/utils/request'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'

const loading = ref(false)
const tableData = ref([])
const formRef = ref(null)
const formState = ref({})
const expandedRowKeys = ref([])
const isExpandAll = ref(false)

const getData = async () => {
  loading.value = true
  const { code, data } = await post('/med/MedicalRecord/getDictMrCategoryList', formState.value)
  loading.value = false
  if (code === 0) {
    tableData.value = data
  }
}

const onExpandAll = () => {
  loading.value = true
  if (isExpandAll.value) {
    isExpandAll.value = false
    expandedRowKeys.value = []
    loading.value = false
  } else {
    setTimeout(() => {
      expandedRowKeys.value = getId(tableData.value)
      isExpandAll.value = true
      loading.value = false
    }, 100)
  }
}

//递归获取所有子节点children获取id
const getId = (data) => {
  const ids = []
  data.forEach((item) => {
    ids.push(item.id)
    if (item.children) {
      ids.push(...getId(item.children))
    }
  })
  return ids
}

onMounted(() => getData())
</script>
